package com.chenjun.designpattern.structural.flyweight;

import java.util.Hashtable;

public class 享元模式
{

	public static void main(String[] args) throws InstantiationException, IllegalAccessException
	{
		FlyweightFactory<String,ConcreteFlyweight> factory = new FlyweightFactory<String,ConcreteFlyweight>();
		Flyweight fly1 = factory.getFlyweight("666",ConcreteFlyweight.class);
		Flyweight fly2 = factory.getFlyweight("777",ConcreteFlyweight.class);
		Flyweight fly3 = factory.getFlyweight("666",ConcreteFlyweight.class);
		
		System.out.println(fly1 == fly2);
		System.out.println(fly1 == fly3);
		
	}
}
	
abstract class Flyweight
{
	
}

/**
 * 用于本模式的抽象数据类型
 * 外部状态
 * @author admin
 *
 */
interface ExtrinsicState
{
}

class ConcreteFlyweight extends Flyweight
{
	
}

class FlyweightFactory<K,V extends Flyweight>
{
	private Hashtable<K,V> flyweights = new Hashtable<K,V>();
	
	public V getFlyweight(K key,Class<? extends Flyweight> clazz) throws InstantiationException, IllegalAccessException
	{
		V v = (V)flyweights.get(key);
		if(v == null)
		{
			v = (V)clazz.newInstance(); 
			flyweights.put(key, v);
		}
		return v;
	}
}
